import React, { useEffect, useState, useCallback } from "react";
import {
  Card,
  Button,
  Divider,
  Table,
  message,
  Space,
  Popconfirm,
  Modal,
  Form,
  Input,
  Upload,
  Row,
  Col
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import TradeRequest from "@/api/production/trademark";
import { RecordsModel } from "@/api/production/model/trademark";
import SkeletonInput from "antd/lib/skeleton/Input";

export default function HospitalSet() {
  let [trade, setTrade] = useState<RecordsModel[]>(); // 表格数据
  let [page, setPage] = useState(1);
  let [limit, setLimit] = useState(10);
  let [total, setTotal] = useState(0);
  let [loading, setLoding] = useState(false);
  let [visible, setvisible] = useState(false);
  let [imageUrl, setImageUrl] = useState("");
  let [form] = Form.useForm();
  let [inputV,setInput] = useState('')
  let [endId,setEndId] = useState(-1)
  // 表格结构
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      className: "column-money",
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      dataIndex: "logoUrl",
      render: (value) => {
        return <img alt="" width="80" src={value} />;
      },
    },
    {
      title: "操作",
      render: (value) => {
        return (
          <Space>
            <Button onClick={editHadler(value)}>编辑</Button>
            <Popconfirm
              title="Are you sure to delete this task?"
              onConfirm={confirm(value)}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="primary"
                danger
                onClick={() => {
                  console.log(value);
                  TradeRequest.getRemove(value.id);
                  tradeInitiali();
                }}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  const confirm = (value: RecordsModel) => {
    return async () => {
      try {
        await TradeRequest.getRemove(value.id!);
        tradeInitiali();
        message.success("删除成功");
      } catch (error) {
        message.error("取消删除");
      }
    };
  };

  // 初始化数据 
  let tradeInitiali = useCallback(async () => {
    try {
      let result = await TradeRequest.getPageList(page, limit);
      setTrade(result.records);
      setTotal(result.total);
    } catch (error) {
      console.log(error);
    }
  }, [page, limit]);
  useEffect(() => {
    tradeInitiali();
  }, [tradeInitiali]);

  
  // 图片的验证
  let beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };
  // 转为base64
  let getBase64 = (img: any, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  // 图片
  let handleChange = (info: any) => {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl:string)=>{
        if (info.fileList[0].response.data) {
          setImageUrl(info.fileList[0].response.data)
        }
      })
    }
  }

  

  // 新增
  let onFinish = async(value:RecordsModel) => {
    let res = {
      tmName:inputV,
      logoUrl:imageUrl,
      id:endId
    }
    try {
      if(endId){
        await TradeRequest.getUpdate(res)
      }else{

        await TradeRequest.getSave(res)
      }
      tradeInitiali()
      setvisible(false)
      form.resetFields();
      setImageUrl('')
      setEndId(-1)
    } catch (error) {
      console.log(error);
    }
  }
  // 取消
  let cancelPlus = () => {
    form.resetFields();
    setImageUrl('')
    setvisible(false)
    setInput('')
  }

  // 编辑
  let editHadler = (value:RecordsModel) => {
   return () => {
    setvisible(true)
    setInput(value.tmName)
    setImageUrl(value.logoUrl)
    setEndId(value.id!)
   }
    
  }
  return (
    <Card>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => {
          setvisible(true);
        }}
      >
        添加
      </Button>
      <Divider />
      <Table
        className="mb-10"
        columns={columns}
        dataSource={trade}
        bordered
        rowKey="id"
        pagination={{
          showTotal: (total) => `总计 ${total} 条`,
          total: total,
          current: page,
          pageSize: limit,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: [10, 20, 30, 40],
          onChange: (page, limit) => {
            setPage(page);
            setLimit(limit);
          },
        }}
      />
      <Modal
        visible={visible}
        title="添加品牌"
        footer={null}
        maskClosable={false}
        onCancel={cancelPlus}
      >
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 12 }} onFinish={onFinish} form={form}>
          <Form.Item label="品牌名称" rules={[{ required: true, message: '品牌名称必须输入!' }]} name="tmName">
            <Input placeholder="请输入品牌名称" value={inputV}/>
          </Form.Item>
          <Form.Item label="品牌LOGO" rules={[{ required: true, message: 'Please input your password!' }]}>
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/dev-api/admin/product/fileUpload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                <PlusOutlined style={{fontSize:30}}/>
              )}
            </Upload>
          </Form.Item>
          <Form.Item >
          <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            
            <Button onClick={cancelPlus}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 8 }} disabled={imageUrl.length < 1}>
              保存
            </Button>

          </Col>
        </Row>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
